#ifdef KITSCHY_DEBUG_MEMORY 
#include "debug_memorymanager.h"
#endif

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "math.h"

#include "BList.h"
#include "BVector.h"
#include "geometrics.h"
#include "quaternion.h"
#include "symbol.h"
#include "sort.h"
#include "ontology.h"
#include "featureterm.h"
#include "FTKBase.h"

#include "AWLocalViewport.h"

#include "AWEntity.h"
#include "AWMessage.h"
#include "AWScenario.h"
#include "AWBody.h"
#include "AWSensor.h"
#include "AWAgentsSensor.h"
#include "AWBrain.h"
#include "AWAgent.h"
#include "AWWorld.h"


AW_AgentsSensor::AW_AgentsSensor(Ontology *O,FTKBase *M) : AW_Sensor(O,M) 
{
	class_name->set("AW_AgentsSensor");

	m_ontology->new_sort("sensed-agent","any",7,"name","symbol",
												"x","float","y","float","z","float",
												"dirx","float","diry","float","dirz","float");
	m_ontology->new_sort("sensed-self","sensed-agent",0);
} /* AW_AgentsSensor */ 


AW_AgentsSensor::AW_AgentsSensor(FILE *fp,Ontology *O,FTKBase *M) : AW_Sensor(O,M)
{
	class_name->set("AW_AgentsSensor");
	load(fp);

	m_ontology->new_sort("sensed-agent","any",7,"name","symbol","x","float","y","float","z","float",
															    "dirx","float","diry","float","dirz","float");
	m_ontology->new_sort("sensed-self","sensed-agent",0);
} /* AW_AgentsSensor */ 


AW_AgentsSensor::~AW_AgentsSensor() 
{
} /* AW_AgentsSensor::~AW_AgentsSensor */ 


List<FeatureTerm> *AW_AgentsSensor::sense(AW_Agent *a,AW_World *w)
{
	List<FeatureTerm> *l1;
	List<Symbol> l2;
	List<Vector> l3,l4;
	Symbol *s;
	Vector *v,*va;
	char tmp[256];

	l1=new List<FeatureTerm>;

	/* Self perception: */ 
	sprintf(tmp,"(define (sensed-self) (name \"%s\") (x %f) (y %f) (z %f) "
													"(dirx %f) (diry %f) (dirz %f))",
													a->get_AgentName()->get(),
													a->get_pos().x,a->get_pos().y,a->get_pos().z,
													a->get_dir().x,a->get_dir().y,a->get_dir().z);
	{
		FeatureTerm *ft=FeatureTerm::fromStringNOOS(tmp,m_memory,m_ontology);
		l1->Add(ft);
	}

	/* Perception of the other agents: */ 
	w->sense_agents(a,&l2,&l3,&l4);
	while(!l2.EmptyP()) {
		s=l2.ExtractIni();
		v=l3.ExtractIni();
		va=l4.ExtractIni();
		sprintf(tmp,"(define (sensed-agent) (name \"%s\") (x %f) (y %f) (z %f) "
													     "(dirx %f) (diry %f) (dirz %f))",
					s->get(),v->x,v->y,v->z,va->x,va->y,va->z);
		{
			FeatureTerm *ft=FeatureTerm::fromStringNOOS(tmp,m_memory,m_ontology);
			l1->Add(ft);
		}
		delete s;
		delete v;
		delete va;
	} /* while */ 

	return l1;
} /* AW_AgentsSensor::Sense */ 


bool AW_AgentsSensor::is_a(char *c)
{
	if (strcmp(c,"AW_AgentsSensor")==0) return true;

	return AW_Sensor::is_a(c);
} /* AW_AgentsSensor::is_a */ 


bool AW_AgentsSensor::is_a(Symbol *c)
{
	if (c->cmp("AW_AgentsSensor")) return true;

	return AW_Sensor::is_a(c);
} /* AW_AgentsSensor::is_a */ 
